package com.y.fund.handler;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.y.fund.service.CommService;
import com.y.fund.utils.StrUtil;

@Component
public class BeanFactoryProxy implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanFactoryProxy.applicationContext = applicationContext;
    }

    public static Object getBean(String beanId) {
        if (StrUtil.isBlankIncNullStr(beanId)) {
            return null;
        }
        return applicationContext != null ? applicationContext.getBean(beanId) : null;
    }

    public static <T> T getBean(Class<T> clazz, String beanId) {
        if (StrUtil.isBlankIncNullStr(beanId)) {
            return null;
        }
        if (applicationContext != null) {
            return (T) applicationContext.getBean(beanId);
        } else {
            return null;
        }
    }

    public static <T> T getBeanByClazz(Class<T> clazz) {
        if (null == clazz) {
            return null;
        }
        if (applicationContext != null) {
            return applicationContext.getBean(clazz);
        } else {
            return null;
        }
    }

    public static <T> Map<String, T> getBeansByClazz(Class<T> clazz) {
        if (null != clazz && null != applicationContext) {
            return applicationContext.getBeansOfType(clazz);
        }

        return new HashMap<>();
    }

    public static Map<String, Object> getBeansByAnnotation(Class<? extends Annotation> clazz) {
        if (null != clazz && null != applicationContext) {
            return applicationContext.getBeansWithAnnotation(clazz);
        }

        return null;
    }


    public static CommService commService() {
        return Holder.COMM_SERVICE;
    }

    private static class Holder {
        private static final CommService COMM_SERVICE = BeanFactoryProxy.getBean(CommService.class, "commService");
    }
}